﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using SMS;
using System.Threading;
using System.IO.Ports;
using System.Configuration;
using System.Timers;
using ChuanYe.Common;
[assembly: log4net.Config.DOMConfigurator(Watch = true)]
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        static bool StartState = false;
        static System.Threading.Timer SiSTimer;
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private void Form1_Load(object sender, EventArgs e)
        {
            label4.Text = "川页短信管理系统已启动,短信服务正在开启请稍后...";
            this.notifyIcon1.Visible = false;
            int TimeInterval = 6000;
            if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["Interval"].ToString()))
            {
                TimeInterval = int.Parse(ConfigurationSettings.AppSettings["Interval"].ToString());
            }
            else
            {
                TimeInterval = 6000;
            }
            SiSTimer = new System.Threading.Timer(new TimerCallback(timerCall), this, 6000, TimeInterval);
        }

        private void timerCall(object obj)
        {
            try
            {
                SmSserver();
                if (StartState)
                {
                    string sql = "SELECT * FROM T_Sms WHERE status=0 ";
                    using (SqlConnection connection =
                       new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]))
                    {
                        SqlCommand command =
                            new SqlCommand(sql, connection);
                        connection.Open();

                        SqlDataReader reader = command.ExecuteReader();

                        // Call Read before accessing data.
                        if (reader.IsClosed == false)
                        {
                            while (reader.Read())
                            {
                                byte[] Msg = UnicodeEncoding.Default.GetBytes(reader["smsinfo"].ToString());
                                byte[] PhoneNo = UnicodeEncoding.Default.GetBytes(reader["phone"].ToString());

                                string smsstr = "";
                                int smssate = SMSClass.SMSQuery(SMSClass.SMSSendMessage(Msg, PhoneNo));
                                if (smssate == 0)
                                {
                                    smsstr = "发送失败";
                                }
                                else
                                {
                                    sql = "UPDATE T_Sms SET status=1";
                                    sql += " WHERE id = " + reader["id"].ToString();
                                    using (SqlConnection conn =
                        new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]))
                                    {
                                        SqlCommand comm =
                                            new SqlCommand(sql, conn);
                                        conn.Open();
                                        comm.ExecuteNonQuery();
                                        conn.Close();
                                        Thread.Sleep(100);
                                    }


                                    smsstr = "发送成功";
                                }
                                this.Invoke((EventHandler)delegate
                                {
                                    dataGridView1.AppendText("发送信息：" + reader["smsinfo"].ToString() + "\r\n");
                                    dataGridView1.AppendText("发送手机：" + reader["phone"].ToString() + "\r\n");
                                    dataGridView1.AppendText("发送人：" + reader["name"].ToString() + "\r\n");
                                    dataGridView1.AppendText("录入时间：" + reader["add_date"].ToString() + "\r\n");
                                    dataGridView1.AppendText("发送时间：" + DateTime.Now.ToString() + "\r\n");
                                    dataGridView1.AppendText("发送状态：" + smsstr + "\r\n");
                                    log.Warn("发送信息：" + reader["smsinfo"].ToString() + "\r\n");
                                    log.Warn("发送手机：" + reader["phone"].ToString() + "\r\n");
                                    log.Warn("发送人：" + reader["name"].ToString() + "\r\n");
                                    log.Warn("发送状态：" + smsstr + "\r\n");
                                    log.Warn("发送时间：" + DateTime.Now.ToString() + "\r\n");
                                    reader.Close();
                                    reader.Dispose();
                                    Thread.Sleep(100);

                                    return;
                                });

                                return;
                            }
                            return;
                        }
                        connection.Close();
                        return;
                    }
                }
                return;
            }
            catch (Exception ee)
            {
                log.Warn(ee.Message);
            }
        }

        private void SmSserver()
        {

            bool model = false;

            if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["Port"].ToString()))
            {

                if (int.Parse(ConfigurationSettings.AppSettings["Port"].ToString()) == 0)
                {
                    model = true;
                }

            }
            else
            {
                model = true;
            }

            if (model == true)
            {

                string[] portlist = SerialPort.GetPortNames();

                foreach (string port in portlist)
                {
                    int ret;
                    int iPort = Convert.ToInt32(port.Substring(3));
                    uint bit = Convert.ToUInt32(ConfigurationSettings.AppSettings["BaudRate"]);
                    int Parity = Convert.ToInt32(ConfigurationSettings.AppSettings["Parity"]);
                    int ByteSize = Convert.ToInt32(ConfigurationSettings.AppSettings["ByteSize"]);
                    int StopBits = Convert.ToInt32(ConfigurationSettings.AppSettings["StopBits"]);
                    int FlowControl = Convert.ToInt32(ConfigurationSettings.AppSettings["FlowControl"]);
                    ret = SMSClass.SMSStartService(iPort, bit, Parity, ByteSize, StopBits, FlowControl, UnicodeEncoding.Default.GetBytes("card"));
                    if (ret == 1)
                    {
                        StartState = true;
                        Invoke(new MethodInvoker(delegate()
                        {
                            label4.Text = "服务启动成功!";
                            log.Warn("服务启动成功\r\n");
                            Thread.Sleep(100);
                        }));
                        txtPort.Text = port.Substring(3);
                        //button2.Enabled = false;
                        //button3.Enabled = false;
                        //SMSClass.SMSStopSerice();
                        return;
                    }
                    else
                    {
                        StartState = false;
                        Byte[] message = new byte[100];
                        SMSClass.SMSGetLastError(message);
                        Invoke(new MethodInvoker(delegate()
                        {
                            label4.Text = "服务启动失败!";
                            log.Warn("服务启动失败\r\n");
                            Thread.Sleep(100);
                        }));
                        button2.Enabled = true;
                        button3.Enabled = true;
                        //SMSClass.SMSStopSerice();
                        return;
                    }
                }
            }
            else
            {
                int ret;
                int iPort = Convert.ToInt32(ConfigurationSettings.AppSettings["Port"]);
                uint bit = Convert.ToUInt32(ConfigurationSettings.AppSettings["BaudRate"]);
                int Parity = Convert.ToInt32(ConfigurationSettings.AppSettings["Parity"]);
                int ByteSize = Convert.ToInt32(ConfigurationSettings.AppSettings["ByteSize"]);
                int StopBits = Convert.ToInt32(ConfigurationSettings.AppSettings["StopBits"]);
                int FlowControl = Convert.ToInt32(ConfigurationSettings.AppSettings["FlowControl"]);
                ret = SMSClass.SMSStartService(iPort, bit, Parity, ByteSize, StopBits, FlowControl, UnicodeEncoding.Default.GetBytes("card"));
                if (ret == 1)
                {
                    StartState = true;
                    Invoke(new MethodInvoker(delegate()
                    {
                        label4.Text = "服务启动成功!";
                        log.Warn("服务启动成功\r\n");
                        Thread.Sleep(100);
                    }));

                    txtPort.Text = iPort.ToString();
                    button2.Enabled = false;
                    button3.Enabled = false;
                    //SMSClass.SMSStopSerice();
                    return;
                }
                else
                {
                    StartState = false;
                    Byte[] message = new byte[100];
                    SMSClass.SMSGetLastError(message);
                    this.Invoke((EventHandler)delegate
                          {
                              label4.Text = "服务启动失败!";
                              log.Warn("服务启动失败\r\n");
                              Thread.Sleep(100);
                          });

                    button2.Enabled = true;
                    button3.Enabled = true;
                    //SMSClass.SMSStopSerice();
                    return;
                }
            }
        }

        private void InitData()
        {
            //string sql = "SELECT * FROM SMS_SENDINFO ORDER BY SENDDATE DESC";
            //SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
            //DataSet ds = new DataSet();
            //sda.Fill(ds);
            //dataGridView1.DataSource = ds;
            //dataGridView1.DataMember = ds.Tables[0].TableName;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int ret;
                if (txtPort.Text != "")
                {
                    int iPort = Convert.ToInt32(ConfigurationSettings.AppSettings["Port"]);
                    uint bit = Convert.ToUInt32(ConfigurationSettings.AppSettings["BaudRate"]);
                    int Parity = Convert.ToInt32(ConfigurationSettings.AppSettings["Parity"]);
                    int ByteSize = Convert.ToInt32(ConfigurationSettings.AppSettings["ByteSize"]);
                    int StopBits = Convert.ToInt32(ConfigurationSettings.AppSettings["StopBits"]);
                    int FlowControl = Convert.ToInt32(ConfigurationSettings.AppSettings["FlowControl"]);
                    ret = SMSClass.SMSStartService(iPort, bit, 2, 8, 0, 0, UnicodeEncoding.Default.GetBytes("card"));
                    if (ret == 1)
                    {
                        label4.Text = "服务启动成功!";
                        log.Warn("服务启动成功\r\n");
                        button2.Enabled = true;
                        button3.Enabled = true;
                        //SMSClass.SMSStopSerice();
                    }
                    else
                    {
                        Byte[] message = new byte[100];
                        SMSClass.SMSGetLastError(message);
                        label4.Text = "服务启动失败!";
                        log.Warn("服务启动失败\r\n");
                        //SMSClass.SMSStopSerice();
                    }
                }
            }
            catch (Exception eee)
            {

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                int ret;
                int iPort = Convert.ToInt32(ConfigurationSettings.AppSettings["Port"]);
                uint bit = Convert.ToUInt32(ConfigurationSettings.AppSettings["BaudRate"]);
                int Parity = Convert.ToInt32(ConfigurationSettings.AppSettings["Parity"]);
                int ByteSize = Convert.ToInt32(ConfigurationSettings.AppSettings["ByteSize"]);
                int StopBits = Convert.ToInt32(ConfigurationSettings.AppSettings["StopBits"]);
                int FlowControl = Convert.ToInt32(ConfigurationSettings.AppSettings["FlowControl"]);
                ret = SMSClass.SMSStartService(1, 115200, 2, 8, 0, 0, UnicodeEncoding.Default.GetBytes("card"));
                if (ret == 1)
                {
                    label4.Text = "服务启动成功!";
                    log.Warn("服务启动成功\r\n");
                    button2.Enabled = true;
                    button3.Enabled = true;
                }
                else
                {
                    Byte[] message = new byte[100];
                    SMSClass.SMSGetLastError(message);
                    label4.Text = "服务启动失败!";
                    log.Warn("服务启动失败\r\n");
                }

                Thread.Sleep(2000);

                string strContent = this.txtContent.Text.Trim();
                string strPhoneNo = this.txtPhoneNo.Text.Trim();
                if (strContent.Equals(""))
                {
                    MessageBox.Show(this, "内容不能为空!", "提示", MessageBoxButtons.OK);
                    return;
                }
                if (strPhoneNo.Equals(""))
                {
                    MessageBox.Show(this, "手机号不能为空!", "提示", MessageBoxButtons.OK);
                    return;
                }
                foreach (string phone in strPhoneNo.Split(','))
                {
                    byte[] Msg = UnicodeEncoding.Default.GetBytes(strContent);
                    byte[] PhoneNo = UnicodeEncoding.Default.GetBytes(phone);
                    SMSClass.SMSSendMessage(Msg, PhoneNo);
                    label4.Text = "正在发送，请等待...";
                }
            }
            catch (Exception ee)
            {
                log.Warn(ee.Message);

            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //SMSClass.SMSStopSerice();
            label4.Text = "停止服务!";
            button2.Enabled = false;
            button3.Enabled = false;
        }

        private void Form1_Deactivate(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
                this.notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {


        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.notifyIcon1.Visible = false;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                SMSClass.SMSStopSerice();
            }
            catch (Exception ec)
            { };

        }
    }
}
